<!--
  - Copyright (C) 2018-2019
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<template>
	<view>
		<cu-custom :bgColor="'bg-'+theme.backgroundColor" :isBack="false">
			<block slot="backText">返回</block>
			<block slot="content">消息</block>
		</cu-custom>
		<view>
			<im-connect></im-connect>
		</view>
		<view class="cu-list menu-avatar">
			<view class="cu-item" :class="modalName=='move-box-'+ index?'move-cur':''"
				v-for="(item,index) in Conversation" :key="index" @touchstart="ListTouchStart"
				@touchmove="ListTouchMove" @touchend="ListTouchEnd" :data-target="'move-box-' + index"
				@click="openChat(item)">
				<view class="cu-avatar round lg" :style="item.faceURL?'background-image:url(' + item.faceURL + ')':''">
					<text class="cuIcon-people" v-if="!item.faceURL"></text>
				</view>
				<!-- <view class="cu-avatar rpinConversationound lg" :style="[{backgroundImage:'url('+item.faceURL+')'}]"></view> -->
				<view class="content">
					<view class="text-grey">
						<text v-if="item.isPinned" class="cuIcon-top text-red text-bold"></text>
						{{ item.showName }}
					</view>
					<view class="text-gray text-sm">{{ item.content }}</view>
				</view>
				<view class="action">
					<view class="text-grey text-xs">{{ item.latestMsgSendTime |formatTimeMsg }}</view>
					<view v-if="item.unreadCount !=0" class="cu-tag round bg-red sm">{{ item.unreadCount }}</view>
				</view>
				<view class="move">
					<view class="bg-grey" @click.stop="pinConversation(item)">{{ item.isPinned ? '取消置顶' : '置顶' }}</view>
					<view class="bg-red" @click.stop="deleteConversation(item)">删除</view>
				</view>
			</view>
		</view>
		<view :class="'cu-load bg-gray ' + (loadmore?'loading':'over')"></view>
	</view>
</template>

<script>
	/**
	 * Copyright (C) 2018-2019
	 * All rights reserved, Designed By www.joolun.com
	 * 注意：
	 * 本软件为www.joolun.com开发研制，未经购买不得使用
	 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
	 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
	 */
	const util = require("utils/util.js");
	const app = getApp();

	import JimUtil from '@/utils/jim-util' // JLIM工具库
	import imConnect from '@/components/chat-message/im-connect' //im连接状态

	export default {
		components: {
			imConnect
		},
		data() {
			return {
				CustomBar: this.CustomBar,
				theme: app.globalData.theme, //全局颜色变量
				IMloginStatus: app.globalData.IMdata.IMloginStatus, //状态
				Conversation: null,
				loadmore: false,
				modalName: null,
				listTouchStart: 0,
				listTouchDirection: null,
				userInfo: uni.getStorageSync('user_info'),
			};
		},
		filters: {
			formatTimeMsg(time) {
				return JimUtil.parseTimeMsg(time);
			},
		},
		watch: {
			IMloginStatus(val) {
				// console.log('IMloginStatus', val)
			},
		},
		onShow() {
			//更新购物车tabar角标数量
			uni.setTabBarBadge({
				index: 3,
				text: app.globalData.shoppingCartCount + ''
			});
			if (!this.userInfo || !this.userInfo.id) {
				uni.reLaunch({
					url: '/pages/login/index'
				});
				return
			}
			app.initJIM().then(res => {
				//刷新会话
				JimUtil.refreshConoversation()
			});
		},
		onLoad(options) {
			this.userInfo = uni.getStorageSync('user_info')
			// 保存别人分享来的 userCode
			util.saveSharerUserCode(options);
			// 收到会话更改，更新会话
			uni.$on('JIMConversation', (data) => {
				this.getConversation()
			})
			//连接断开监听
			uni.$on('JIMDisconnect', (data) => {
				this.getConversation();
			})
			//登录监听
			uni.$on('JIMLogin', (data) => {
				this.getConversation();
			})
		},
		onUnload() {
			// uni.off('JIMLogin')
			// uni.off('JIMDisconnect')
			// uni.off('JIMConversation')
		},

		methods: {
			// 打开聊天
			openChat(item) {
				uni.navigateTo({
					url: '/pages/message/chat/index?chatUserId=' + item.userID + '&showName=' + item.showName
				})
			},
			getConversation() {
				let that = this;
				let JIM = app.globalData.JIM;
				this.loadmore = true
				try {
					if (app.globalData.IMdata.IMloginStatus) {
						JIM.getAllConversationList().then((res) => {
							if (res.errCode == 0) {
								const data = JSON.parse(res.data);
								this.Conversation = data
								JimUtil.saveConversationList(data)
							}
							that.loadmore = false
						}).catch(err => {
							this.Conversation = JimUtil.getConversationList()
							that.loadmore = false
						});
					} else {
						this.Conversation = JimUtil.getConversationList()
						that.loadmore = false
					}
				} catch (e) {
					this.Conversation = JimUtil.getConversationList()
					that.loadmore = false
				}
			},
			pinConversation(item) { //置顶或取消置顶
				const options = {
					conversationID: item.conversationID,
					isPinned: !item.isPinned
				}
				let JIM = app.globalData.JIM;
				JIM.pinConversation(options).then(({
					data
				}) => {
					this.getConversation()
				}).catch(err => {})
			},
			deleteConversation(item) { //删除会话
				let that = this
				let JIM = app.globalData.JIM;
				uni.showModal({
					content: '是否删除该聊天？',
					cancelText: '我再想想',
					confirmColor: '#ff0000',
					success(res) {
						if (res.confirm) {
							JimUtil.deleteConversation(item)
							JIM.deleteConversationFromLocalAndSvr(item.conversationID).then(({
								data
							}) => {
								that.getConversation()
							}).catch(err => {})
						}
					}
				});
			},
			// ListTouch触摸开始
			ListTouchStart(e) {
				this.listTouchStart = e.touches[0].pageX
			},

			// ListTouch计算方向
			ListTouchMove(e) {
				this.listTouchDirection = e.touches[0].pageX - this.listTouchStart > 0 ? 'right' : 'left'
			},

			// ListTouch计算滚动
			ListTouchEnd(e) {
				if (this.listTouchDirection == 'left') {
					this.modalName = e.currentTarget.dataset.target
				} else {
					this.modalName = null
				}
				this.listTouchDirection = null
			}
		}
	};
</script>
<style>

</style>
